import { typedHttp } from '@/utils/typedHttp';

interface RiskGuaranteeRelationResponse {
  id: string;
  risk_item_id: string;
  guarantee_item_id: string;
  created_at: string;
}

/**
 * 获取指定风险项的所有关联关系
 * @param riskId 风险项ID
 * @returns 关联关系列表
 */
export const getRiskRelations = async (riskId: string): Promise<RiskGuaranteeRelationResponse[]> => {
  return typedHttp.get<RiskGuaranteeRelationResponse[]>(`/relations/risk/${riskId}`);
};

/**
 * 创建风险与保障关联关系
 * @param riskId 风险项ID
 * @param guaranteeId 保障项ID
 * @returns 创建的关联关系
 */
export const createRiskRelation = async (
  riskId: string,
  guaranteeId: string
): Promise<RiskGuaranteeRelationResponse> => {
  return typedHttp.post<RiskGuaranteeRelationResponse>('/relations/', {
    risk_item_id: riskId,
    guarantee_item_id: guaranteeId,
  });
};

/**
 * 删除关联关系
 * @param relationId 关联关系ID
 */
export const deleteRiskRelation = async (relationId: string): Promise<void> => {
  return typedHttp.delete(`/relations/${relationId}`);
};

/**
 * 更新风险项的所有保障关联
 * @param riskId 风险项ID
 * @param guaranteeIds 保障项ID数组
 * @returns 更新后的关联关系列表
 */
export const updateRiskRelations = async (
  riskId: string,
  guaranteeIds: string[]
): Promise<RiskGuaranteeRelationResponse[]> => {
  // 先获取现有的关联关系
  const existingRelations = await getRiskRelations(riskId);
  const existingGuaranteeIds = new Set(existingRelations.map(r => r.guarantee_item_id));
  const newGuaranteeIds = new Set(guaranteeIds);

  // 需要删除的关联
  const relationsToDelete = existingRelations.filter(
    relation => !newGuaranteeIds.has(relation.guarantee_item_id)
  );

  // 需要添加的关联
  const guaranteesToAdd = Array.from(newGuaranteeIds).filter(
    id => !existingGuaranteeIds.has(id)
  );

  // 并行执行所有删除和添加操作
  await Promise.all([
    ...relationsToDelete.map(relation => deleteRiskRelation(relation.id)),
    ...guaranteesToAdd.map(guaranteeId => createRiskRelation(riskId, guaranteeId)),
  ]);

  // 返回更新后的关联关系
  return getRiskRelations(riskId);
};
